﻿using PARK.Common.Enum;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.Expand.Thirdparty;
using PARK.Expand.Thirdparty.Email;
using PARK.Expand.Thirdparty.Email.Model;
using PARK.FriendlyException;
using PARK.JsonSerialization;
using PARK.System.Entitys.Dto.System.SysConfig;
using PARK.System.Entitys.System;
using PARK.System.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.System.Entitys.Model.Permission.User;
using PARK.Common.Core.Manager;

namespace PARK.System.Service.System
{
    /// <summary>
    /// 系统配置
    /// 版 本：V3.2
    /// 日 期：2021-06-01 
    /// </summary>
    [ApiDescriptionSettings(Tag = "System", Name = "SysConfig", Order = 211)]
    [Route("api/system/[controller]")]
    public class SysConfigService : ISysConfigService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<SysConfigEntity> _sysConfigRepository;
        private readonly SqlSugarScope _db;

        /// <summary>
        /// 初始化一个<see cref="SysConfigService"/>类型的新实例
        /// </summary>
        /// <param name="sysConfigRepository"></param>
        public SysConfigService(ISqlSugarRepository<SysConfigEntity> sysConfigRepository)
        {
            _sysConfigRepository = sysConfigRepository;
            _db = _sysConfigRepository.Context;
        }

        #region GET
        /// <summary>
        /// 获取系统配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("")]
        public async Task<SysConfigOutput> GetInfo()
        {
            var user = new UserInfo();
            await Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;

                var _userManager = App.GetService<IUserManager>(services);

                user = await _userManager.GetUserInfo();
            });
            var array = new Dictionary<string, string>();
            var data = await _sysConfigRepository.Entities.Where(x => x.Category.Equals("WxPayConfig") && x.CompanyId.Equals(user.companyId)).ToListAsync();
            foreach (var item in data)
            {
                array.Add(item.Key, item.Value);
            }
            var data1 = await _sysConfigRepository.Entities.Where(x => x.Category.Equals("QHConfig") && x.CompanyId.Equals(user.companyId)).ToListAsync();
            foreach (var item in data1)
            {
                array.Add(item.Key, item.Value);
            }
            var output = array.Serialize().Deserialize<SysConfigOutput>();
            return output;
        }

        #endregion

        #region Post

        /// <summary>
        /// 邮箱链接测试
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Email/Test")]
        public void EmailTest([FromBody] SysConfigEmailTestInput input)
        {
            var mailAccount = input.Adapt<MailAccount>();
            if ("1".Equals(input.ssl))
            {
                mailAccount.Ssl = true;
            }
            else
            {
                mailAccount.Ssl = false;
            }
            var result = Mail.CheckConnected(mailAccount);
            if (!result)
                throw PARKException.Oh(ErrorCode.D9003);
        }

        /// <summary>
        /// 钉钉链接测试
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("testDingTalkConnect")]
        public void testDingTalkConnect([FromBody] SysConfigDingTestInput input)
        {
            var dingUtil = new Ding(input.dingSynAppKey, input.dingSynAppSecret);
            if (string.IsNullOrEmpty(dingUtil.token))
                throw PARKException.Oh(ErrorCode.D9003);
        }

        /// <summary>
        /// 更新系统配置（基本设置）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task Update([FromBody] SysConfigBasisInput input)
        {
            var user = new UserInfo();
            await Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;

                var _userManager = App.GetService<IUserManager>(services);

                user = await _userManager.GetUserInfo();
            });
            var configDic = input.Adapt<Dictionary<string, object>>();
            var entitys = new List<SysConfigEntity>();
            //设备心跳周期
            var eqheart = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "qinhua_eq_heart" && p.Category == "QHConfig" && p.CompanyId == user.companyId);
            if (eqheart != null)
            {
                eqheart.Value = input.qinhua_eq_heart;
                var isOk = await _db.Updateable(eqheart).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "qinhua_eq_heart";
                sConfigEntity.Value = input.qinhua_eq_heart;
                sConfigEntity.Category = "QHConfig";
                sConfigEntity.Name = "设备心跳周期";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //脱机最多笔数
            var eqofflinemax = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "qinhua_eq_offline_max" && p.Category == "QHConfig" && p.CompanyId == user.companyId);
            if (eqofflinemax != null)
            {
                eqofflinemax.Value = input.qinhua_eq_offline_max;
                var isOk = await _db.Updateable(eqofflinemax).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "qinhua_eq_offline_max";
                sConfigEntity.Value = input.qinhua_eq_offline_max;
                sConfigEntity.Category = "QHConfig";
                sConfigEntity.Name = "脱机最多笔数";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //脱机单笔最大金额
            var eqofflinemoney = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "qinhua_eq_offline_max_money" && p.Category == "QHConfig" && p.CompanyId == user.companyId);
            if (eqofflinemoney != null)
            {
                eqofflinemoney.Value = input.qinhua_eq_offline_max_money;
                var isOk = await _db.Updateable(eqofflinemoney).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "qinhua_eq_offline_max_money";
                sConfigEntity.Value = input.qinhua_eq_offline_max_money;
                sConfigEntity.Category = "QHConfig";
                sConfigEntity.Name = "脱机单笔最大金额";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //消费机软件版本
            var appversion= await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "qinhua_app_version" && p.Category == "QHConfig" && p.CompanyId == user.companyId);
            if (appversion != null)
            {
                appversion.Value = input.qinhua_app_version;
                var isOk = await _db.Updateable(appversion).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "qinhua_app_version";
                sConfigEntity.Value = input.qinhua_app_version;
                sConfigEntity.Category = "QHConfig";
                sConfigEntity.Name = "消费机软件版本";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //消费机软件地址
            var appurl = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "qinhua_app_url" && p.Category == "QHConfig" && p.CompanyId == user.companyId);
            if (appurl != null)
            {
                appurl.Value = input.qinhua_app_url;
                var isOk = await _db.Updateable(appurl).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "qinhua_app_url";
                sConfigEntity.Value = input.qinhua_app_url;
                sConfigEntity.Category = "QHConfig";
                sConfigEntity.Name = "消费机软件地址";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //每日定时
            var apptiming = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "qinhua_app_timing" && p.Category == "QHConfig" && p.CompanyId == user.companyId);
            if (apptiming != null)
            {
                apptiming.Value = input.qinhua_app_timing;
                var isOk = await _db.Updateable(apptiming).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "qinhua_app_timing";
                sConfigEntity.Value = input.qinhua_app_timing;
                sConfigEntity.Category = "QHConfig";
                sConfigEntity.Name = "每日定时";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //支付码有效时间(秒)
            var appqrocode = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "qinhua_app_qrcode" && p.Category == "QHConfig" && p.CompanyId == user.companyId);
            if (appqrocode != null)
            {
                appqrocode.Value = input.qinhua_app_qrcode;
                var isOk = await _db.Updateable(appqrocode).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "qinhua_app_qrcode";
                sConfigEntity.Value = input.qinhua_app_qrcode;
                sConfigEntity.Category = "QHConfig";
                sConfigEntity.Name = "支付码有效时间(秒)";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

        }

        /// <summary>
        /// 更新系统配置（小程序设置）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("Updateapp")]
        public async Task Updateapp([FromBody] SysConfigAppInput input)
        {
            var user = new UserInfo();
            await Scoped.Create(async (_, scope) =>
            {
                var services = scope.ServiceProvider;

                var _userManager = App.GetService<IUserManager>(services);

                user = await _userManager.GetUserInfo();
            });
            var configDic = input.Adapt<Dictionary<string, object>>();

            //小程序ID
            var appid = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "wx_appid" && p.Category == "WxPayConfig" && p.CompanyId == user.companyId);
            if (appid != null)
            {
                appid.Value = input.wx_appid;
                var isOk = await _db.Updateable(appid).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "wx_appid";
                sConfigEntity.Value = input.wx_appid;
                sConfigEntity.Category = "WxPayConfig";
                sConfigEntity.Name = "小程序ID";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //小程序秘钥
            var appsercet = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "wx_app_secret" && p.Category == "WxPayConfig" && p.CompanyId == user.companyId);
            if (appsercet != null)
            {
                appsercet.Value = input.wx_app_secret;
                var isOk = await _db.Updateable(appsercet).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "wx_app_secret";
                sConfigEntity.Value = input.wx_app_secret;
                sConfigEntity.Category = "WxPayConfig";
                sConfigEntity.Name = "小程序秘钥";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //微信商户Id
            var appmchid = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "wx_mch_id" && p.Category == "WxPayConfig" && p.CompanyId == user.companyId);
            if (appmchid != null)
            {
                appmchid.Value = input.wx_mch_id;
                var isOk = await _db.Updateable(appmchid).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "wx_mch_id";
                sConfigEntity.Value = input.wx_mch_id;
                sConfigEntity.Category = "WxPayConfig";
                sConfigEntity.Name = "微信商户Id";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //微信支付回调
            var wxpayresult = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "wx_pay_resulturl" && p.Category == "WxPayConfig" && p.CompanyId == user.companyId);
            if (wxpayresult != null)
            {
                wxpayresult.Value = input.wx_pay_resulturl;
                var isOk = await _db.Updateable(wxpayresult).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "wx_pay_resulturl";
                sConfigEntity.Value = input.wx_pay_resulturl;
                sConfigEntity.Category = "WxPayConfig";
                sConfigEntity.Name = "微信支付回调";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //微信支付Secret
            var wxmchkey = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "wx_mch_key" && p.Category == "WxPayConfig" && p.CompanyId == user.companyId);
            if (wxmchkey != null)
            {
                wxmchkey.Value = input.wx_mch_key;
                var isOk = await _db.Updateable(wxmchkey).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "wx_mch_key";
                sConfigEntity.Value = input.wx_mch_key;
                sConfigEntity.Category = "WxPayConfig";
                sConfigEntity.Name = "微信支付Secret";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }

            //微信支付服务器地址
            var wxmpaysvrip = await _db.Queryable<SysConfigEntity>().FirstAsync(p => p.Key == "wx_pay_svrip" && p.Category == "WxPayConfig" && p.CompanyId == user.companyId);
            if (wxmpaysvrip != null)
            {
                wxmpaysvrip.Value = input.wx_pay_svrip;
                var isOk = await _db.Updateable(wxmpaysvrip).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            }
            else
            {
                var sConfigEntity = new SysConfigEntity();
                sConfigEntity.Key = "wx_pay_svrip";
                sConfigEntity.Value = input.wx_pay_svrip;
                sConfigEntity.Category = "WxPayConfig";
                sConfigEntity.Name = "微信支付服务器地址";
                sConfigEntity.Id = YitIdHelper.NextId().ToString();
                sConfigEntity.CompanyId = user.companyId;
                sConfigEntity.CompanyName = user.companyName;
                var isOk = await _db.Insertable(sConfigEntity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
            }
        }


        #endregion

        #region PublicMethod

        /// <summary>
        /// 系统配置信息
        /// </summary>
        /// <param name="category">分类</param>
        /// <param name="key">键</param>
        /// <returns></returns>
        [NonAction]
        public async Task<SysConfigEntity> GetInfo(string category, string key)
        {
            return await _sysConfigRepository.FirstOrDefaultAsync(s => s.Category == category && s.Key == key);
        }

        #endregion

        #region PrivateMethod

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="entitys"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        private async Task Save(List<SysConfigEntity> entitys, string category)
        {
            try
            {
                _sysConfigRepository.Context.Ado.BeginTran();
                await _sysConfigRepository.DeleteAsync(x => x.Category.Equals(category));
                await _sysConfigRepository.InsertAsync(entitys);
                _sysConfigRepository.Context.Ado.CommitTran();
            }
            catch (Exception)
            {
                _sysConfigRepository.Context.Ado.RollbackTran();
            }
        }
        #endregion
    }
}
